package com.lxy.gateway.filter;

import cn.hutool.json.JSONObject;
import com.lxy.gateway.service.LagouUserServiceFeginClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.util.List;

//import com.lxy.common.JsonResult;
//import com.lxy.user.service.LagouTokenService;

/**
 * @author 123
 * @date 2020/6/29 23:05
 * @description
 */
@Component
@Slf4j
public class TokenAuthFilter implements GlobalFilter, Ordered {



    @Autowired
    private LagouUserServiceFeginClient lagouUserServiceFeginClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders headers = request.getHeaders();
        List<String> cookies = headers.get("Cookie");
        if (cookies == null || cookies.isEmpty()) {
            return chain.filter(exchange);
        }
        String token = cookies.get(0).split("=")[1];
        String jsonResult = lagouUserServiceFeginClient.authToken(token);
        JSONObject jsonObject = new JSONObject(jsonResult);
        if ("200".equals(jsonObject.getStr("code"))) {
            jsonObject.put("code", "301");
            response.setStatusCode(HttpStatus.OK); // 状态码
            DataBuffer wrap = null;
            try {
                wrap = response.bufferFactory().wrap(jsonObject.toString().getBytes("utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(wrap));
        }
        return chain.filter(exchange);
    }


    @Override
    public int getOrder() {
        return 1;
    }
}
